package response

import (
	"github.com/adwindone/sdk-go/model/evm"
	"github.com/adwindone/sdk-go/util/hexutil"
	"math/big"
)

type Receipt struct {
	TransactionHash     string      `json:"transaction_hash"`      // 交易哈希
	TransactionIndex    uint64      `json:"transaction_index"`     // 交易索引
	BlockHash           string      `json:"block_hash"`            // 区块哈希
	BlockNumber         uint64      `json:"block_number"`          // 区块高度
	CumulativeQuotaUsed hexutil.Big `json:"cumulative_quota_used"` // 累计消耗的配额
	QuotaUsed           hexutil.Big `json:"quota_used"`            // 消耗的配额
	ContractAddress     string      `json:"contract_address"`      // 合约地址
	Logs                []*Log      `json:"logs"`                  // 日志
	StateRoot           string      `json:"state_root"`            // 地址
	LogsBloom           []byte      `json:"logs_bloom"`            // 日志过滤器
	ErrorMessage        string      `json:"error_message"`         // 错误信息
}

type Log struct {
	Address             string   `json:"address"`               // 地址
	Topics              [][]byte `json:"topics,omitempty"`      // 主题
	Data                []byte   `json:"data"`                  // 数据
	BlockHash           string   `json:"block_hash"`            // 区块哈希
	BlockNumber         uint64   `json:"block_number"`          // 区块高度
	TransactionHash     string   `json:"transaction_hash"`      // 交易哈希
	TransactionIndex    uint64   `json:"transaction_index"`     // 交易索引
	LogIndex            uint64   `json:"log_index"`             // 日志索引
	TransactionLogIndex uint64   `json:"transaction_log_index"` // 交易日志索引
}

func ReceiptConvert(receipt *evm.Receipt) *Receipt {
	if receipt == nil {
		return nil
	}
	// 累计消耗的Quota
	cQuota := new(big.Int)
	cQuota.SetBytes(receipt.CumulativeQuotaUsed)
	// 消耗的Quota
	quota := new(big.Int)
	quota.SetBytes(receipt.QuotaUsed)
	// 转换
	info := new(Receipt)
	info.TransactionHash = hexutil.Encode(receipt.TransactionHash)
	info.TransactionIndex = receipt.TransactionIndex
	info.BlockHash = hexutil.Encode(receipt.BlockHash)
	info.BlockNumber = receipt.BlockNumber
	info.CumulativeQuotaUsed = hexutil.Big(*cQuota)
	info.QuotaUsed = hexutil.Big(*quota)
	info.ContractAddress = hexutil.Encode(receipt.ContractAddress)
	info.Logs = LogsConvert(receipt.Logs)
	info.StateRoot = hexutil.Encode(receipt.StateRoot)
	info.LogsBloom = receipt.LogsBloom
	info.ErrorMessage = receipt.ErrorMessage
	return info
}

func LogsConvert(logs []*evm.Log) []*Log {
	if logs == nil {
		return nil
	}
	var result []*Log
	for _, log := range logs {
		info := new(Log)
		info.Address = hexutil.Encode(log.Address)
		info.Topics = log.Topics
		info.Data = log.Data
		info.BlockHash = hexutil.Encode(log.BlockHash)
		info.BlockNumber = log.BlockNumber
		info.TransactionHash = hexutil.Encode(log.TransactionHash)
		info.TransactionIndex = log.TransactionIndex
		info.LogIndex = log.LogIndex
		info.TransactionLogIndex = log.TransactionLogIndex
		result = append(result, info)
	}
	return result
}
